package br.com.agenda.support.user;

import java.util.List;

import javax.inject.Inject;
import javax.inject.Named;

import org.apache.log4j.Logger;
import org.primefaces.event.SelectEvent;
import org.springframework.context.annotation.Scope;
import org.springframework.web.context.WebApplicationContext;

import br.com.agenda.model.UserEntity;
import br.com.agenda.model.repositories.IUserRepository;
import br.com.agenda.model.utils.BaseBeans;

@Scope(value = WebApplicationContext.SCOPE_SESSION)
@Named(value = "userMB")
public class UserMB extends BaseBeans {

	private static final long serialVersionUID = 1L;
	
	private static final Logger logger = Logger.getLogger(UserMB.class);
	
	@Inject
	private IUserRepository userRepository;
	
	private List<UserEntity> users;
	
	private UserEntity selectedUser;
	
	private Long id;
	
	public UserMB(){
		
	}
	
	public void onLoad(){
		this.users = this.userRepository.findAll();
	}
	
	public List<UserEntity> getUsers(){
		return this.users;
	}
	
	public Long getID(){
		return this.id;
	}
	
	public void setID(Long id){
		this.id = id;
	}
	
	public void delete(){
		if(this.selectedUser != null){
			this.userRepository.delete(this.selectedUser.getId());
		}
	}
	
	public void selectUser(SelectEvent evt){
		try{
			if(evt.getObject() != null){
				this.selectedUser = (UserEntity) evt.getObject();
			}else{
				this.selectedUser = null;
			}
		}catch(Exception e){
			this.selectedUser = null;
			
			logger.error(e.getMessage(), e);
		}
	}
	
	public void unselectUser(){
		this.selectedUser = null;
	}
	
	public UserEntity getSelectedUser(){
		return this.selectedUser;
	}
	
	public void setSelectedUser(UserEntity selectedUser){
		this.selectedUser = selectedUser;
	}
}
